import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCSelect {
    public static void main(String[] args) throws SQLException {
        //1.初始化数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java107?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root"); //设置用户名
        ((MysqlDataSource)dataSource).setPassword("jzh020829");   //设置密码



        //2.建立连接
        Connection connection = dataSource.getConnection();



        //3.构造sql
        String sql = "select * from student";
        PreparedStatement statement = connection.prepareStatement(sql);




        //4.执行sql
        ResultSet resultSet = statement.executeQuery();//resultSet可以作为查询结果的临时表


        //5.遍历结果集合
        while (resultSet.next()){
            //把resultSet想象成一个表格
            //每次调用next，光标往下走一行
            //当光标指向某一行的时候，通过getxxx获取数据
            int id = resultSet.getInt("id");//括号里面可以写列的名字或列的下标
            String name = resultSet.getString("name");
            System.out.println("id = "+id+", name = "+name);

        }

        //6.释放资源
        resultSet.close();
        statement.close();
        connection.close();


    }
}





